package com.xuhai.blog.common.shiro;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 4.shiro核心配置类
 * @Author PangJunjie
 * @Date 2022/2/9/009
 */
@Configuration
public class ShiroConfig {
    /*shiro核心管理器*/
    @Bean("securityManager")
    public SecurityManager securityManager(Shiro2Realm shiro2Realm){
        /*初始化管理器*/
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        /*配置自定义验证规则*/
        securityManager.setRealm(shiro2Realm);
        /*取消记住我功能*/
        securityManager.setRememberMeManager(null);
        /*返回管理器*/
        return securityManager;
    }

    /*shiro核心过滤器*/
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
        /*初始化过滤器工厂*/
        ShiroFilterFactoryBean shiroFilter=new ShiroFilterFactoryBean();
        /*配置管理器*/
        shiroFilter.setSecurityManager(securityManager);
        /*初始化过滤方式对象集合*/
        Map<String, Filter> filterMap = new HashMap<>();
        /*设置过滤器规则名称,此时，验证规则为oauth2则表示必须登录才可以进行，匿名访问的规则名是固定的：anon*/
        filterMap.put("oauth2",new Shiro2Filter());
        /*存入工厂*/
        shiroFilter.setFilters(filterMap);

        /*初始化过滤请求集合*/
        Map<String, String> filters=new LinkedHashMap<>();
        filters.put("/admin/kaptcha.jpg","anon");
        filters.put("/admin/login","anon");
        filters.put("/img/**","anon");
        filters.put("/api/**","anon");
        /*需要验证的规则一般都是全部拦截，所以必须写在其他规则的后面*/
        filters.put("/**","oauth2");
        /*存入工厂*/
        shiroFilter.setFilterChainDefinitionMap(filters);
        return shiroFilter;
    }
}
